#include "Fraction.h"
#include <fstream>
#include <iostream>


using namespace std;

// 默认构造函数
Fraction::Fraction() : num(0), denom(1) {}

// 接受两个整数作为参数的构造函数
Fraction::Fraction(int num, int denom) : num(num), denom(denom) {
    if (denom == 0) {
        cout << "注意:分母不能为零，此分数无意义（用1/0标记）。"<< endl;
    }
    simplify();
}

// 拷贝构造函数
Fraction::Fraction(const Fraction& other) : num(other.num), denom(other.denom) {}

// 算术运算符：+ - * /
Fraction Fraction::operator+(const Fraction& other) const {
    return Fraction(num * other.denom + other.num * denom, denom * other.denom);
}

Fraction Fraction::operator-(const Fraction& other) const {
    return Fraction(num * other.denom - other.num * denom, denom * other.denom);
}

Fraction Fraction::operator*(const Fraction& other) const {
    return Fraction(num * other.num, denom * other.denom);
}

Fraction Fraction::operator/(const Fraction& other) const {
    if (other.num == 0) {
        cout << "注意:除数不能为零。"<< endl;
    }
    return Fraction(num * other.denom, denom * other.num);
}

// 关系运算符： < <= == != >= >
bool Fraction::operator<(const Fraction& other) const {
    if (num < 0 && other.num < 0) {
        return num * other.denom > other.num * denom;
    } else {
        return num * other.denom < other.num* denom;
    }
}

bool Fraction::operator<=(const Fraction& other) const {
    if (num < 0 && other.num < 0) {
        return num * other.denom >= other.num * denom;
    } else {
        return num * other.denom <= other.num * denom;
    }
}

bool Fraction::operator==(const Fraction& other) const {
    return num * other.denom == other.num * denom;
}

bool Fraction::operator!=(const Fraction& other) const {
    return !(*this == other);
}

bool Fraction::operator>=(const Fraction& other) const {
    return !(*this <= other);
}

bool Fraction::operator>(const Fraction& other) const {
    return !(*this <= other);
}

// 转换为 double 类型
Fraction::operator double() const {
    return static_cast<double>(num) / denom;
}

// 转换为字符串
string Fraction::toStr() const {
    string result;
    result += to_string(num);
    result += "/";
    result += to_string(denom);
    return result;
}

// 流插入和提取器
ostream& operator<<(ostream& out, const Fraction& f) {
    out << f.toStr();
    return out;
}

istream& operator>>(istream& in, Fraction& f) {
    char division;
    int num,denom;
    in >> num >> division >> denom;
    f = Fraction(num,denom);
    return in;
}

// 从有限小数字符串进行转换
Fraction Fraction::fromDec(double dec) {
    const int precision = 1000000;  // 自定义的精度
    int num = static_cast<int>(dec * precision);
    int denom = precision;
    Fraction result(num, denom);
    result.simplify();
    return result;
}

// 化简分数
void Fraction::simplify() {
    if (denom < 0) {
        num *= -1;
        denom *= -1;
    }
    int a = num;
    int b = denom;
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    int gcd_num = (a > 0) ? a : -a;
    num /= gcd_num;
    denom /= gcd_num;
}
